<template>
  <div :class="[$store.state.appPrefix + '-c-video-preview-modal']" v-if="visible" @click="handleBackdropClick">
    <div class="modal-content" @click.stop>
      <!-- 弹窗头部 -->
      <div class="modal-header">
        <h3 class="modal-title">{{ title }}</h3>
        <button class="close-btn" @click="closeModal">&times;</button>
      </div>

      <!-- 弹窗内容 -->
      <div class="modal-body">
        <!-- 视频播放器 -->
        <div class="video-container" v-if="videoUrl">
          <video
            ref="videoPlayer"
            :src="videoUrl"
            controls
            preload="metadata"
            class="preview-video"
            controlsList="nodownload noplaybackrate nofullscreen"
            @loadedmetadata="onVideoLoaded"
            @error="onVideoError"
            @play="onVideoPlay"
            @pause="onVideoPause"
          >
            您的浏览器不支持视频播放
          </video>

          <!-- 视频未播放时显示预览图 -->
          <div class="video-poster" v-if="screenshotUrl && !isPlaying">
            <img :src="screenshotUrl" alt="视频预览" class="poster-image" />
            <div class="play-overlay">
              <button class="play-button" @click="playPause">
                <span class="play-icon">▶</span>
              </button>
            </div>
          </div>
        </div>

        <!-- 截图预览（当没有视频时） -->
        <div class="screenshot-container" v-if="screenshotUrl && !videoUrl">
          <img :src="screenshotUrl" alt="截图预览" class="screenshot-image" />
        </div>

        <!-- 加载状态 -->
        <div class="loading" v-if="loading">
          <div class="spinner"></div>
          <span>加载中...</span>
        </div>

        <!-- 错误状态 -->
        <div class="error" v-if="error">
          <div class="error-icon">⚠️</div>
          <p>{{ error }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'VideoPreviewModal',
  props: {
    // 是否显示弹窗
    visible: {
      type: Boolean,
      default: false
    },
    // 弹窗标题
    title: {
      type: String,
      default: '视频预览'
    },
    // 视频URL
    videoUrl: {
      type: String,
      default: ''
    },
    // 截图URL
    screenshotUrl: {
      type: String,
      default: ''
    },
    // 是否允许点击背景关闭
    closeOnBackdrop: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      loading: false,
      error: '',
      isPlaying: false
    }
  },
  computed: {
    downloadUrl() {
      return this.videoUrl || this.screenshotUrl
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.loading = true
        this.error = ''
        this.isPlaying = false
      } else {
        this.stopVideo()
      }
    },
    videoUrl() {
      if (this.videoUrl) {
        this.loading = true
        this.error = ''
      }
    }
  },
  methods: {
    // 关闭弹窗
    closeModal() {
      this.$emit('close')
    },

    // 处理背景点击
    handleBackdropClick(event) {
      if (this.closeOnBackdrop && event.target === event.currentTarget) {
        this.closeModal()
      }
    },

    // 视频加载完成
    onVideoLoaded() {
      this.loading = false
      this.$emit('video-loaded', {
        duration: this.$refs.videoPlayer.duration,
        videoWidth: this.$refs.videoPlayer.videoWidth,
        videoHeight: this.$refs.videoPlayer.videoHeight
      })
    },

    // 视频加载错误
    onVideoError(event) {
      this.loading = false
      this.error = '视频加载失败，请检查文件格式或网络连接'
      this.$emit('video-error', event)
    },

    // 视频开始播放
    onVideoPlay() {
      this.isPlaying = true
    },

    // 视频暂停
    onVideoPause() {
      this.isPlaying = false
    },

    // 播放/暂停控制
    playPause() {
      if (this.$refs.videoPlayer) {
        if (this.isPlaying) {
          this.$refs.videoPlayer.pause()
        } else {
          this.$refs.videoPlayer.play()
        }
        this.isPlaying = !this.isPlaying
      }
    },

    // 停止视频
    stopVideo() {
      if (this.$refs.videoPlayer) {
        this.$refs.videoPlayer.pause()
        this.$refs.videoPlayer.currentTime = 0
        this.isPlaying = false
      }
    },

    // 下载文件
    downloadFile() {
      if (this.downloadUrl) {
        const link = document.createElement('a')
        link.href = this.downloadUrl
        link.download = this.getFileName()
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)

        this.$emit('file-downloaded', this.downloadUrl)
      }
    },

    // 获取文件名
    getFileName() {
      const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-')
      if (this.videoUrl) {
        return `video-${timestamp}.webm`
      } else if (this.screenshotUrl) {
        return `screenshot-${timestamp}.png`
      }
      return `file-${timestamp}`
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (!bytes) return ''
      if (bytes === 0) return '0 Bytes'
      const k = 1024
      const sizes = ['Bytes', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / (k ** i)).toFixed(2)) + ' ' + sizes[i]
    },

    // 格式化时长
    formatDuration(seconds) {
      if (!seconds) return ''
      const hours = Math.floor(seconds / 3600)
      const minutes = Math.floor((seconds % 3600) / 60)
      const secs = Math.floor(seconds % 60)

      if (hours > 0) {
        return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
      } else {
        return `${minutes}:${secs.toString().padStart(2, '0')}`
      }
    }
  }
}
</script>
